package com.link2room.aeriabots.controller.wxReception;

import com.link2room.aeriabots.facade.IWxCallBackFacadeService;
import com.link2room.common.util.HttpUtil;
import com.link2room.common.util.StringUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 微信 推送Callback
 * Created by LN on 2016/9/18.
 */
@RestController
@RequestMapping("/{appid}")
public class WxCallbackController {
    @Resource(name="wxCallBackFacadeService")
    private IWxCallBackFacadeService wxCallBackFacadeService;
    @Resource(name="wxCallBackWechatPublishFcadeService")
    private IWxCallBackFacadeService wxCallBackWechatPublishFcadeService;


    @RequestMapping("/callback")
    public void callBack(
            @PathVariable String appid,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception{
        String resStr = null;
        try{
            String conunt = request.getParameter("count");
            String msgSignature = request.getParameter("msg_signature");
            String nonce =request.getParameter("nonce");
            String timeStamp =request.getParameter("timestamp");
            String body = HttpUtil.getRequestBody(request);
            String xml =wxCallBackFacadeService.wxMsgCryptDecryptMsg(msgSignature, timeStamp, nonce, body);
            if("wx570bc396a51b8ff8".equals(appid)){
                //全网发布测试
                resStr = wxCallBackWechatPublishFcadeService.wxCallBackHandller(xml);
            }else {
                resStr = wxCallBackFacadeService.wxCallBackHandller(xml);
            }
        }catch (Exception e){
            throw e;
        }finally {
            returnSuccess(response,resStr);
        }
    }

    private void returnSuccess(HttpServletResponse response,String resStr) throws IOException {


        PrintWriter write = response.getWriter();
        if(StringUtil.isNotBlank(resStr)){

            write.write(resStr);
        }else{
            write.write("success");

        }
        write.flush();
        write.close();
    }
}
